<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <style type="text/css">
        body, html {
            width: 100%;
            height: 100%;
            margin: 0;
            font-family: "微软雅黑";
        }

        #allmap {
            width: 100%;
            height: 500px;
            overflow: hidden;
        }

        #result {
            width: 100%;
            font-size: 12px;
        }

        dl, dt, dd, ul, li {
            margin: 0;
            padding: 0;
            list-style: none;
        }

        p {
            font-size: 12px;
        }

        dt {
            font-size: 14px;
            font-family: "微软雅黑";
            font-weight: bold;
            border-bottom: 1px dotted #000;
            padding: 5px 0 5px 5px;
            margin: 5px 0;
        }

        dd {
            padding: 5px 0 0 5px;
        }

        li {
            line-height: 28px;
        }

        .searchbox-content {
            width: 368px;
            border-radius: 2px 0 0 2px;
            background: #fff;
        }

        #searchbox #searchbox-container {
            position: relative;
            z-index: 2;
            pointer-events: auto;
            width: 216px;
            float: left;
            box-sizing: border-box;
            box-shadow: 1px 2px 1px rgba(0, 0, 0, .15);
        }

        #sole-searchbox-content #suggestId {
            box-sizing: border-box;
            border: 0;
            padding: 9px 0;
            border-left: 10px solid transparent;
            border-right: 10px solid transparent;
            line-height: 20px;
            font-size: 16px;
            height: 38px;
            color: #333;
            position: relative;
            border-radius: 2px 0 0 2px;
        }

        .searchbox-content .searchbox-content-common {
            box-sizing: border-box;
            float: left;
            width: 217px;
            height: 38px;
        }

        #searchbox #search-button {
            pointer-events: auto;
            background: url(http://webmap0.map.bdstatic.com/wolfman/static/common/images/new/searchbox_f175577.png) no-repeat 0 -76px #3385ff;
            width: 57px;
            height: 38px;
            float: left;
            border: 0;
            padding: 0;
            cursor: pointer;
            border-radius: 0 2px 2px 0;
            box-shadow: 1px 2px 1px rgba(0, 0, 0, .15);
        }

        .clearfix {
            position: absolute;
            top: 0px;
            right: 0px;
        }
    </style>
    <script type="text/javascript"
            src="http://api.map.baidu.com/api?v=2.0&ak=d1pistIRVscsFaX4YjNPhn3MSBzO5DfG"></script>
    <!--加载鼠标绘制工具-->
    <script type="text/javascript"
            src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
    <link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css"/>
    <!--加载检索信息窗口-->
    <script type="text/javascript"
            src="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.js"></script>
    <link rel="stylesheet" href="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.css"/>
    <title>鼠标绘制工具</title>
</head>
<body>
<div id="allmap" style="width: 760px;height: 365px"></div>
<div id="searchbox" class="clearfix">
    <div id="searchbox-container">
        <div id="sole-searchbox-content" class="searchbox-content">
            <input id="suggestId" class="searchbox-content-common" type="text" name="word" autocomplete="off"
                   maxlength="256" placeholder="搜地点" value="">
            <div id="searchResultPanel"
                 style="border:1px solid #C0C0C0;width:215px;height:auto; display:none;"></div>
        </div>
    </div>
    <button id="search-button" data-title="搜索" data-tooltip="1"></button>
</div>
<script src="../../plugins/jQuery/jquery-2.2.3.min.js"></script>
<script type="text/javascript">
    // 百度地图API功能
    function getQueryString(name) {
        var result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
        if (result == null || result.length < 1) {
            return "";
        }
        return result[1];
    }

    var coordinate = getQueryString("coordinate");
    var type = getQueryString("type");
    var map = new BMap.Map('allmap');
    var points, line = [];
    map.enableScrollWheelZoom();
    if (type == 0) {
        var x, y;
        x = coordinate.split(",");
        y = x[1];
        x = x[0];
        map.centerAndZoom(x + y, 13);
    }
    else {
        sessionStorage.setItem("points", coordinate);//记录当前坐标集用于比较
        points = coordinate.split(";");
        var endPoint;

        points.forEach(function (value, index, array) {
            if (value != "") {
                line.push(new BMap.Point(value.split(",")[0], value.split(",")[1]));
                endPoint = value;
            }
        });

        var polyline = new BMap.Polyline(line, {strokeColor: "blue", strokeWeight: 2, strokeOpacity: 0.5});
        map.addOverlay(polyline);

        var p = new BMap.Point(points[0].split(",")[0], points[0].split(",")[1]);
        map.centerAndZoom(p, 16);

        /***************设置起始图标*****************/

        if (!isOnePoint(points)) {
            setIcon('../../images/start.png', points[0]);
            setIcon('../../images/end.png', endPoint);
        } else
            setIcon('../../images/start.png', points[0]);


        /***************设置起始图标*****************/

    }


    function setIcon(pic, point) {
        var icon = new BMap.Icon(pic, new BMap.Size(40, 33), {//是引用图标的名字以及大小，注意大小要一样
            anchor: new BMap.Size(12, 30)//这句表示图片相对于所加的点的位置
        });
        var mkr = new BMap.Marker(new BMap.Point(point.split(",")[0], point.split(",")[1]), {
            icon: icon
        });
        map.addOverlay(mkr);
    }

    function isOnePoint(points) {
        var flag = 0;
        for (var i in points) {
            if (points[i] != "")
                flag++;
        }
        return flag < 2;
    }


    function addMapControl() {
        //向地图中添加缩放控件
        var ctrl_nav = new BMap.NavigationControl({anchor: BMAP_ANCHOR_TOP_LEFT, type: BMAP_NAVIGATION_CONTROL_LARGE});
        map.addControl(ctrl_nav);

        //向地图中添加比例尺控件
        var ctrl_sca = new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_LEFT, enableGeolocation: true});
        map.addControl(ctrl_sca);

        var geolocationControl = new BMap.GeolocationControl();
        geolocationControl.addEventListener("locationSuccess", function (e) {

        });
        geolocationControl.addEventListener("locationError", function (e) {
            // 定位失败事件
            alert(e.message);
        });
        map.addControl(geolocationControl);

    }

    addMapControl();

    /*******************划线框************************/
    if (type != 3) {//非查看模式显示划线框

        BMapLib.DrawingManager.prototype._bindMarker = function () {

            var me = this,
                map = this._map,
                mask = this._mask;

            /**
             * 鼠标点击的事件
             */
            var clickAction = function (e) {
                // 往地图上添加marker
                var marker = new BMap.Marker(e.point, me.markerOptions);
                map.addOverlay(marker);
                marker.addEventListener("dragend", function (e) {
                    console.log(e.point.lng + "," + e.point.lat);
                    sessionStorage.setItem("points", e.point.lng + "," + e.point.lat);
                });
                me._dispatchOverlayComplete(marker);
            };
            mask.addEventListener('click', clickAction);
        };

        var overlays = [];

        var overlaycomplete = function (e) {
            var path = [], points = "";
            map.removeOverlay(overlays.pop());
            if (e.overlay.toString().indexOf("Marker") >= 0)
                path.push(e.overlay.point);
            else
                path = e.overlay.getPath();
            overlays.push(e.overlay);
            for (var i = 0; i < path.length; i++) {
                points += path[i].lng + ',' + path[i].lat + ';';
            }
            var geoc = new BMap.Geocoder();
            var pt = new BMap.Point(path[0].lng, path[0].lat);
            geoc.getLocation(pt, function (rs) {
                var addComp = rs.addressComponents;
                sessionStorage.setItem("roadName", addComp.street);
            });
            sessionStorage.setItem("points", points);
            sessionStorage.setItem("flag", 1);

        };
        var styleOptions = {
            strokeColor: "red",    //边线颜色。
            fillColor: "red",      //填充颜色。当参数为空时，圆形将没有填充效果。
            strokeWeight: 3,       //边线的宽度，以像素为单位。
            strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。
            fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
            strokeStyle: 'solid' //边线的样式，solid或dashed。
        };
        //实例化鼠标绘制工具
        var drawingManager = new BMapLib.DrawingManager(map, {
            isOpen: false, //是否开启绘制模式
            enableDrawingTool: true, //是否显示工具栏
            drawingToolOptions: {
                anchor: BMAP_ANCHOR_BOTTOM_RIGHT, //位置
                offset: new BMap.Size(5, 5), //偏离值
                drawingModes: [BMAP_DRAWING_POLYLINE, BMAP_DRAWING_MARKER] //设置画线模式

            },
            polylineOptions: styleOptions, //线的样式
            markerOptions: {enableDragging: true}
        });

        $(".BMapLib_Drawing_panel").append("<a style=\"\n" +
            "    border-right: 1px solid #d2d2d2;\n" +
            "    float: left;\n" +
            "    height: 100%;\n" +
            "    width: 64px;\n" +
            "    height: 100%;\n" +
            "    background-image: url(../../images/white_x.png);\n" +
            "    cursor: pointer;\n" +
            "    background-size: 64px 100%;\n" +
            "    background-repeat:no-repeat;\n" +
            "\" title=\"清除\" onclick=\"clearAll()\"  id=\"cleanLineBtn\" ></a>");

        //添加鼠标绘制工具监听事件，用于获取绘制结果
        drawingManager.addEventListener('overlaycomplete', overlaycomplete);

        //drawingManager.addEventListener('markercomplete', overlaycomplete);

        function clearAll() {
            map.removeOverlay(overlays.pop());
        }

    }

    /*******************划线框************************/

    /******************搜索框*********************/
    //搜索
    function G(id) {
        return document.getElementById(id);
    }

    var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
        {
            "input": "suggestId"
            , "location": map
        });

    ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
        var str = "";
        var _value = e.fromitem.value;
        var value = "";
        if (e.fromitem.index > -1) {
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
        }
        str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

        value = "";
        if (e.toitem.index > -1) {
            _value = e.toitem.value;
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
        }
        str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
        G("searchResultPanel").innerHTML = str;
    });


    var myValue;
    ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
        var _value = e.item.value;
        myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
        G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
        setPlace();
    });

    $("#search-button").click(function () {
        myValue = $("#suggestId").val();
        setPlace();
    });

    $("#suggestId").keydown(function (event) {
        if (event.keyCode == 13) {
            myValue = $("#suggestId").val();
            setPlace();
        }
    });

    function setPlace() {
        // map.clearOverlays();   //清除地图上所有覆盖物
        //$.drawPiont();
        function myFun() {
            var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
            map.centerAndZoom(pp, 15);
            var m = new BMap.Marker(pp);
            map.addOverlay(m);    //添加标注
            m.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
        }

        var local = new BMap.LocalSearch(map, { //智能搜索
            onSearchComplete: myFun
        });
        local.search(myValue);
    }

    /******************搜索框*********************/
</script>
</body>
</html>